//
//  ExtraServiceSettingViewController.m
//  sdkDemo
//
//  Created by rockeyyan on 2019/8/23.
//  Copyright © 2019年 qqconnect. All rights reserved.
//

#import "ExtraServiceSettingViewController.h"
#import "SDKCall.h"
#import "QQAPIShareEntry.h"
#import "ExtraLoadDataViewController.h"

static NSInteger const ExServiceTag_ServiceId  = 10300;
static NSInteger const ExServiceTag_OpenId     = 10301;
static NSInteger const ExServiceTag_ToUin      = 10302;
static NSInteger const ExServiceTag_JsonString = 10303;

#pragma mark - ExServiceCellModel
@interface ExServiceCellModel : NSObject

@property (nonatomic, assign) int cellTag;
@property (nonatomic, copy) NSString *cellKey;
@property (nonatomic, copy) NSString *cellValue;

+ (ExServiceCellModel *)createCellModelForTag:(int)tag key:(NSString *)key value:(NSString *)value;
- (CGFloat)cellHeight;

@end

@implementation ExServiceCellModel

+ (ExServiceCellModel *)createCellModelForTag:(int)tag key:(NSString *)key value:(NSString *)value {
    ExServiceCellModel *resultModel = [ExServiceCellModel new];
    resultModel.cellTag = tag;
    resultModel.cellKey = key;
    resultModel.cellValue = value;
    return resultModel;
}

- (CGFloat)cellHeight {
    if (self.cellTag == ExServiceTag_JsonString) {
        return 300;
    }
    return 60;
}

@end





#pragma mark - ExServiceTableCell

@interface ExServiceTableCell : UITableViewCell

@property (nonatomic, strong) ExServiceCellModel *cellModel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextField *editTextfield;
@property (nonatomic, strong) UITextView *textView;

- (void)loadCellWithModel:(ExServiceCellModel *)cellInfo;
- (NSString *)textResult;

@end

@implementation ExServiceTableCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self.contentView addSubview:self.titleLabel];
        [self.contentView addSubview:self.editTextfield];
        [self.contentView addSubview:self.textView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat cellWidth = self.frame.size.width;
    CGFloat cellHeight = self.frame.size.height;
    self.titleLabel.frame = CGRectMake(10, (cellHeight-13)/2, 60, 13);
    
    CGFloat textTopMargin = 8;
    CGRect textFrame = CGRectMake(CGRectGetMaxX(_titleLabel.frame)+2.f, textTopMargin, cellWidth-CGRectGetMaxX(_titleLabel.frame)-15.f, cellHeight - (textTopMargin * 2));
    self.editTextfield.frame = textFrame;
    
    self.textView.frame = textFrame;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)loadCellWithModel:(ExServiceCellModel *)cellModel {
    self.cellModel = cellModel;
    self.titleLabel.text = cellModel.cellKey;
    
    if (cellModel.cellTag == ExServiceTag_JsonString) {
        self.textView.text = cellModel.cellValue;
        [self addSubview:self.textView];
        [self.editTextfield removeFromSuperview];
    } else {
        self.editTextfield.text = cellModel.cellValue;
        [self addSubview:self.editTextfield];
        [self.textView removeFromSuperview];
    }
    [self setNeedsLayout];
}

- (NSString *)textResult {
    if (self.cellModel.cellTag == ExServiceTag_JsonString) {
        return self.textView.text;
    }
    return self.editTextfield.text;
}

#pragma mark - Getter and setter

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 60, 13)];
        _titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12.f];
    }
    return _titleLabel;
}

- (UITextField *)editTextfield {
    if (!_editTextfield) {
        _editTextfield = [[UITextField alloc] init];
        _editTextfield.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.f];
        _editTextfield.layer.borderWidth = 0.5f;
        _editTextfield.layer.borderColor = [UIColor grayColor].CGColor;
        _editTextfield.layer.cornerRadius = 3.0;
        _editTextfield.layer.masksToBounds = YES;
    }
    return _editTextfield;
}

- (UITextView *)textView {
    if (!_textView) {
        _textView = [[UITextView alloc] init];
        _textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _textView.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.f];
        _textView.layer.borderWidth = 0.5f;
        _textView.layer.borderColor = [UIColor grayColor].CGColor;
        _textView.layer.cornerRadius = 3.0;
        _textView.layer.masksToBounds = YES;
    }
    return _textView;
}

@end




#pragma mark - ExtraServiceSettingViewController

@interface ExtraServiceSettingViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UILabel *tipsLabel;
@property (nonatomic, strong) UIButton *loadDataButton;

@property (nonatomic, copy) NSArray *dataSource;
@property (nonatomic, copy) NSString *serviceId;
@property (nonatomic, copy) NSString *openId;
@property (nonatomic, copy) NSString *toUin;
@property (nonatomic, copy) NSString *jsonString;

@end

@implementation ExtraServiceSettingViewController

- (instancetype)init {
    if (self = [super init]) {
        self.serviceId = @"3007";
        self.openId = [TencentOAuth sharedInstance].openId;
        self.jsonString = @"{\n \"bizType\": 1,\n \"guildId\": \"101010\",\n \"guildName\": \"工会名称\",\n \"joinTroopIntro\": \"加群备注\" \n}";
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    self.navigationItem.title = self.isNewExtendService ? @"新扩展服务" : @"扩展服务";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.confirmButton];
    [self.view addSubview:self.tipsLabel];
    [self.view addSubview:self.loadDataButton];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEvent:)];
    [self.view addGestureRecognizer:tap];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    CGFloat screenWidth = CGRectGetWidth(self.view.frame);
    CGFloat screenHeight = CGRectGetHeight(self.view.frame);
    self.tableView.frame = CGRectMake(0, 0, screenWidth, screenHeight - 140);
    self.tipsLabel.frame = CGRectMake(20, CGRectGetMaxY(self.tableView.frame) + 10, screenWidth - 40, 40);
    
    self.confirmButton.frame = CGRectMake(20, CGRectGetMaxY(self.tipsLabel.frame) + 10, (screenWidth / 2) - 40, 44);
    self.loadDataButton.frame = CGRectMake(CGRectGetMaxX(self.confirmButton.frame) + 40, CGRectGetMaxY(self.tipsLabel.frame) + 10, (screenWidth / 2) - 40, 44);
}

#pragma mark - Public and privite methods

- (void)initData {
    NSMutableArray *cellModels = [NSMutableArray array];
    ExServiceCellModel *serviceIdCellModel = [ExServiceCellModel createCellModelForTag:ExServiceTag_ServiceId key:@"ServiceID: " value:self.serviceId];
    [cellModels addObject:serviceIdCellModel];
    
    if (!self.isNewExtendService) {
        ExServiceCellModel *openIdCellModel = [ExServiceCellModel createCellModelForTag:ExServiceTag_OpenId key:@"OpenID: " value:self.openId];
        [cellModels addObject:openIdCellModel];
        
        ExServiceCellModel *toUinCellModel = [ExServiceCellModel createCellModelForTag:ExServiceTag_ToUin key:@"toUin: " value:self.toUin];
        [cellModels addObject:toUinCellModel];
    }
    
    ExServiceCellModel *jsonStringCellModel = [ExServiceCellModel createCellModelForTag:ExServiceTag_JsonString key:@"json数据: " value:self.jsonString];
    [cellModels addObject:jsonStringCellModel];
    self.dataSource = [cellModels copy];
}

- (CGFloat)cellTotalHeight {
    CGFloat cellTotalHeight = 0;
    for (ExServiceCellModel *cellModel in self.dataSource) {
        cellTotalHeight += [cellModel cellHeight];
    }
    return cellTotalHeight;
}

- (ExServiceCellModel *)cellModelWithRow:(NSInteger)row {
    if (self.dataSource.count <= row) {
        return nil;
    }
    return self.dataSource[row];
}

- (void)loadResult {
    for (NSInteger i = 0; i < self.dataSource.count; i++) {
        ExServiceTableCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        if (cell.tag == ExServiceTag_ServiceId) {
            self.serviceId = [cell textResult];
        }
        if (cell.tag == ExServiceTag_OpenId) {
            self.openId = [cell textResult];
        }
        if (cell.tag == ExServiceTag_ToUin) {
            self.toUin = [cell textResult];
        }
        if (cell.tag == ExServiceTag_JsonString) {
            self.jsonString = [cell textResult];
        }
    }
}

#pragma mark - Events

- (void)tapEvent:(UITapGestureRecognizer *)tap {
    [self.view endEditing:YES];
}

- (void)confirmButtonEvent:(UIButton *)sender {
    if (_openId.length <= 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先授权登录后再操作！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;
    }
    [self loadResult];
    if (self.jsonString.length <= 0) {
        return;
    }
    NSData *jsonData = [self.jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *extendInfo = [NSJSONSerialization JSONObjectWithData:jsonData
                                                               options:NSJSONReadingMutableContainers
                                                                 error:&error];
    
    NSDictionary *userInfo = @{
        @"openId":_openId ?: @"",
        @"serviceId":_serviceId?:@"0",
        @"toUin": _toUin ?: @"",
        @"isNewExtendService": @(self.isNewExtendService),
        @"extendInfo": extendInfo ?: @{}
    };
    [QQApiExtraServiceEntry StartCallApiExtraService:userInfo];
}

- (void)loadDataButtonEvent:(UIButton *)sender {
    ExtraLoadDataViewController *loadDataVC = [[ExtraLoadDataViewController alloc] init];
    [self.navigationController pushViewController:loadDataVC animated:YES];
}

#pragma mark - UITableViewDelegate、UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ExServiceCellModel *cellModel = [self cellModelWithRow:indexPath.row];
    return [cellModel cellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ExServiceCellModel *cellModel = [self cellModelWithRow:indexPath.row];
    NSString *cellIdentifier = @"SdkExtraServiceEditCell";
    ExServiceTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ExServiceTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.tag = cellModel.cellTag;
    }
    [cell loadCellWithModel:cellModel];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Getter and setter

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollEnabled = NO;
        _tableView.contentInset = UIEdgeInsetsMake(64+34, 0, 0, 0);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _tableView;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _confirmButton.layer.cornerRadius = 6;
        _confirmButton.layer.borderWidth = 0.8f;
        _confirmButton.layer.borderColor = [UIColor grayColor].CGColor;
        _confirmButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16];
        [_confirmButton setTitle:@"发 送 到 手 Q" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirmButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

- (UILabel *)tipsLabel {
    if (!_tipsLabel) {
        UILabel *tipsLabel = [[UILabel alloc] init];
        tipsLabel.textColor = [UIColor grayColor];
        tipsLabel.textAlignment = NSTextAlignmentLeft;
        tipsLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:13];
        tipsLabel.text = @"Tips：ServiceID为必填字段，支持的类型请参照官网文档说明。";
        tipsLabel.numberOfLines = 0;
        _tipsLabel = tipsLabel;
    }
    return _tipsLabel;
}

- (UIButton *)loadDataButton {
    if (!_loadDataButton) {
        _loadDataButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loadDataButton.layer.cornerRadius = 6;
        _loadDataButton.layer.borderWidth = 0.8f;
        _loadDataButton.layer.borderColor = [UIColor grayColor].CGColor;
        _loadDataButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16];
        [_loadDataButton setTitle:@"加载json数据" forState:UIControlStateNormal];
        [_loadDataButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_loadDataButton addTarget:self action:@selector(loadDataButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loadDataButton;
}

@end
